package main

import (
	"fmt"
	"github.com/atotto/clipboard"
	"two-factor-auth/lib"
)

func addAction() {
	if lib.CmdArgs.Secret == "" {
		panic("秘钥不能为空")
	}
	lib.Add(lib.CmdArgs.Name, lib.CmdArgs.Secret)
}

func rmAction() {
	lib.Rm(lib.CmdArgs.Name)
}

func runAction() {
	// 判断是否有传值
	secret := lib.CmdArgs.Secret
	if secret == "" {
		// 读取配置
		secret = lib.GetSecret()
	}
	pwd := lib.Cul(secret)
	if lib.CmdArgs.Copy {
		_ = clipboard.WriteAll(fmt.Sprintf("%06d", pwd))
	}
	if !lib.CmdArgs.Silent {
		fmt.Printf("%06d\n", pwd)
	}

}
func lsAction() {
	for name := range lib.GetConfig() {
		fmt.Printf("\t %s:%s\n", name, lib.GetConfig()[name])
	}
}

func helpAction() {
	for cmd, tip := range lib.OptsActionMap {
		fmt.Printf("  %s: %s\n", cmd, tip)
	}
}

func main() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()
	switch lib.CmdArgs.Opt {
	case "add":
		addAction()
	case "run":
		runAction()
	case "rm":
		rmAction()
	case "ls":
		lsAction()
	case "help":
		helpAction()
	}
}
